use colored::Colorize;
use log::{Metadata, Record};
use std::sync::Once;

struct ColoredLogger;

impl log::Log for ColoredLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= log::Level::Info
    }

    fn log(&self, record: &Record) {
        let local = chrono::Local::now();
        let formatted_time = local.format("%Y-%m-%d %H:%M:%S");
        if self.enabled(record.metadata()) {
            let level = record.level();
            let msg = format!("{} - {:>5} - {}", formatted_time, level, record.args());
            match level {
                log::Level::Error => println!("{}", msg.red()),
                log::Level::Warn => println!("{}", msg.yellow()),
                log::Level::Info => println!("{}", msg.green()),
                log::Level::Debug => println!("{}", msg.blue()),
                log::Level::Trace => println!("{}", msg.magenta()),
            }
        }
    }

    fn flush(&self) {}
}

static LOGGER_INIT: Once = Once::new();

pub fn init_logger() {
    LOGGER_INIT.call_once(|| {
        log::set_boxed_logger(Box::new(ColoredLogger)).expect("Failed to initialize logger");
        log::set_max_level(log::LevelFilter::Info);
    });
}
